package com.example.admin.goodnews.fragment.WuLiaoDianWo;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.example.admin.goodnews.R;
import com.example.admin.goodnews.adapter.ChatAdapter;
import com.example.admin.goodnews.database.ChatDBHelper;
import com.example.admin.goodnews.database.ChatDBManager;
import com.example.admin.goodnews.entity.ChatDataEntity;
import com.example.admin.goodnews.entity.MessageEntity;
import com.example.admin.goodnews.utils.GetCurrentTimeUtil;
import com.example.admin.goodnews.utils.HttpUtils;
import com.example.admin.goodnews.utils.NetWorkDataUrl;
import com.google.gson.Gson;

import java.util.List;

/**
 * 图灵机器人页面
 * Created by admin on 2016/10/21.
 */

public class TuLingJiQiRenFragment extends Fragment {
    private RecyclerView recyclerview_tuling;
    private ChatDataEntity chatDataEntity;// 图灵机器人的回复
    private EditText et_message;// 发送消息的EditText
    private Button btn_send;// 发送消息的按钮
    private ChatAdapter chatAdapter;
    private LinearLayoutManager linearLayoutManager;// 布局管理器
    private String time = GetCurrentTimeUtil.getCurrentTime();// 获取系统当前时间
    private String message;// 我发送的消息
    private ChatDBHelper chatDBHelper;
    private SQLiteDatabase sQLiteDatabase;
    private ChatDBManager chatDBManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_tulingjiqiren, null);
        view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        recyclerview_tuling = (RecyclerView) view.findViewById(R.id.recyclerview_tuling);
        linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerview_tuling.setLayoutManager(linearLayoutManager);// 设置布局管理器
        et_message = (EditText) view.findViewById(R.id.et_message);


        btn_send = (Button) view.findViewById(R.id.btn_send);
        // EditText监听事件
        TextChange textChange = new TextChange();
        et_message.addTextChangedListener(textChange);

        chatDBHelper = new ChatDBHelper(getActivity());
        sQLiteDatabase = chatDBHelper.getReadableDatabase();
        chatDBManager = new ChatDBManager(chatDBHelper, sQLiteDatabase);

        setData();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 消息发送按钮点击事件
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chatDBManager.insertdata("我", message, 1);// 向数据库中插入我发送的消息
                getReply();// 获取机器人的回复并将数据插入数据库
                chatAdapter.notifyDataSetChanged();
                setData();
                et_message.setText("");
            }
        });
    }

    // 获取图灵机器人的回复
    private void getReply() {
        String param = NetWorkDataUrl.TULINGJIQIREN_PARAM1 + message + NetWorkDataUrl.TULINGJIQIREN_PARAM2 + time + NetWorkDataUrl.TULINGJIQIREN_PARAM3;
        try {
            HttpUtils.doPostAsyn(NetWorkDataUrl.TULINGJIQIREN_URL, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    chatDataEntity = gson.fromJson(result, ChatDataEntity.class);
                    if (chatDataEntity.getShowapi_res_body().getText() != null) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 初始化适配器并设置数据
    private void setData() {
        List<MessageEntity> chatlist = chatDBManager.querydata();
        chatAdapter = new ChatAdapter(getActivity(), chatlist);
        recyclerview_tuling.setAdapter(chatAdapter);
        chatAdapter.notifyDataSetChanged();
        linearLayoutManager.scrollToPosition(chatlist.size() - 1);// 设置数据更新后显示底部
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    chatDBManager.insertdata("图灵机器人", chatDataEntity.getShowapi_res_body().getText(), 0);
                    setData();
                    break;
            }
        }
    };

    private class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() > 0) {
                btn_send.setEnabled(true);
            } else {
                btn_send.setEnabled(false);
            }
            message = et_message.getText().toString();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

}
